using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class PersonnelAdministration_AddNewUser : System.Web.UI.Page
{
    #region Handlers

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void cuwMain_CreatedUser(object sender, EventArgs e)
    {
        MembershipUser createdUser = Membership.GetUser(cuwMain.UserName);
        SaveUserRoles(createdUser);
    }
    
    protected void cuwMain_ContinueButtonClick(object sender, EventArgs e)
    {
        MembershipUser createdUser = Membership.GetUser(cuwMain.UserName);
        CheckBox ckbActive = cuwMain.CompleteStep.ContentTemplateContainer.FindControl("ckbActive") as CheckBox;
        
        if (ckbActive != null)
        {
            createdUser.IsApproved = ckbActive.Checked;
            Membership.UpdateUser(createdUser);
        }

        Response.Redirect("~/ProfileAdministration/UserAdministration.aspx");
    }

    #endregion 

    #region Methods

    private void SaveUserRoles(MembershipUser user)
    {
        if (user != null)
        {
            List<string> rolesToAdd = new List<string>();
            List<string> rolesToRemove = new List<string>();

            foreach (ListItem item in ckblRoles.Items)
            {
                if (item.Selected == true)
                {
                    if (!Roles.IsUserInRole(user.UserName, item.Value))
                    {
                        rolesToAdd.Add(item.Value);
                    }
                }
                else
                {
                    if (Roles.IsUserInRole(user.UserName, item.Value))
                    {
                        rolesToRemove.Add(item.Value);
                    }
                }
            }

            if (rolesToAdd.Count > 0)
            {
                Roles.AddUserToRoles(user.UserName, rolesToAdd.ToArray());
            }
            if (rolesToRemove.Count > 0)
            {
                Roles.RemoveUserFromRoles(user.UserName, rolesToRemove.ToArray());
            }
        }
    }

    #endregion 
}
